package com.gdut.huayan.security;

import com.gdut.huayan.constant.SecurityConstant;
import com.gdut.huayan.entity.dto.Result;
import com.gdut.huayan.utils.RedisUtils;
import com.gdut.huayan.utils.SecurityUtils;
import com.gdut.huayan.utils.WebJsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SysLogoutHandler implements LogoutSuccessHandler, LogoutHandler {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        response.setHeader(SecurityConstant.AUTHORIZATION_HEADER, null);
        WebJsonUtils.write(response, Result.success());
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String userId = SecurityUtils.getUserId();
        redisUtils.remove(SecurityConstant.USER_PREFIX + userId);
    }
}
